package com.tma.internship.connectserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.tma.internship.ClassesInfo.FileInfo;
import com.tma.internship.activities.R;


import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.SeekBar;

public class ContactServer {
	private List<NameValuePair> data;
	private Context context;
	private Handler handle;
	private static final int HANDLER_SUCCESS = 1;
	private static final int HANDLER_TIME_OUT = 0;
	private ProgressDialog pd = null;
	private Integer[] currentPage;
	public ContactServer(List<NameValuePair> data, Context context){
		this.data = data;
		this.context = context;
		currentPage = new Integer[1];
		handle = new Handler(){
			 public void handleMessage(Message msg) {
                 if (msg.what == HANDLER_SUCCESS)
                 {
                         pd.dismiss();
                 }
                 else if (msg.what == HANDLER_TIME_OUT)
                 {
                         if (!pd.isShowing()) return;
                         else {
                                 pd.dismiss();
                         }
                 }
			 }
		};
	}
	private void progressShow(){
		pd = ProgressDialog.show(context, context.getString(R.string.waiting), context.getString(R.string.loading)
				, true,false);
	}
	public void receiveText(final ServiceCallback<String> callback,String action){
		progressShow();
		new ReceiveTextFromServer(data, action) {
			
			@Override
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				callback.onSuccess(result);
				handle.sendEmptyMessage(HANDLER_SUCCESS);
			}
			
			@Override
			public void onFailure(Exception exception) {
				// TODO Auto-generated method stub
				callback.onFailure(exception);
				handle.sendEmptyMessage(HANDLER_TIME_OUT);
			}
		}.start();
	}
	public void receiveFile(ServiceCallback<File> callback,String action,int page){
		progressShow();
	}
	public void receiveMultipleFile(final ServiceCallback<Integer[]> callback,String action,final String fileName,final int page,final SeekBar downloadBar,final int start) throws InterruptedException{

		Thread thread = new Thread(){
			public void run(){
				final int[] dataInfo = new int[1];
				dataInfo[0] = 0;//size
				for (int i = start ; i < page ; i++){
					//data.remove()
					
					for (int j = 0 ; j < data.size() ; j++ ){
						NameValuePair tmp = data.get(j);
						if (tmp.getName() == "page"){
							data.remove(tmp);
						}
					}	
					
					data.add(0,new BasicNameValuePair("page", i+""));
					currentPage[0] = i;
					
					ReceiveFileFromServer thrFile = new ReceiveFileFromServer(data, ServerInfo.downloadFile, fileName, i,context) {
						
						@Override
						public void onSuccess(Integer result) {
							// TODO Auto-generated method stub
							Log.d("finish a file", currentPage[0]+"");
							int percent = (int)((currentPage[0]+1)*100.0/page);
							downloadBar.setProgress(percent);
							callback.onSuccess(currentPage);
							Log.e("curr", currentPage[0]+"");
							dataInfo[0] += result;
						}
						
						@Override
						public void onFailure(Exception exception) {
							// TODO Auto-generated method stub
							exception.printStackTrace();
						}
					};
					thrFile.start();
					try {
						thrFile.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (currentPage[0] == -1) break;
					
				}
				try {
					FileInputStream fis = context.openFileInput("config");			
					ObjectInputStream ois = new ObjectInputStream(fis);
					List<FileInfo> listFile = (List<FileInfo>) ois.readObject();
					FileInfo fInfo = new FileInfo(fileName, dataInfo[0], page, true);
					//FileInfo tmp = null;
					for (int i = 0 ; i < listFile.size() ; i++){
						if (listFile.get(i).getName().equals(fInfo.getName())) {
							listFile.remove(i);
							break;
						}
					}
					listFile.add(fInfo);
					FileOutputStream fos = context.openFileOutput("config", Context.MODE_PRIVATE);
					ObjectOutputStream oos = new ObjectOutputStream(fos);
					oos.writeObject(listFile);
					oos.close();
					ois.close();
					fis.close();
					fos.close();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					try {
						FileOutputStream fos = context.openFileOutput("config", Context.MODE_PRIVATE);
						ObjectOutputStream oos = new ObjectOutputStream(fos);
						List<FileInfo> listFile = new ArrayList<FileInfo>();
						FileInfo fInfo = new FileInfo(fileName, dataInfo[0], page, true);
						listFile.add(fInfo);
						oos.writeObject(listFile);
						oos.close();
						fos.close();
						e1.printStackTrace();
					} catch (Exception e2){
						e2.printStackTrace();
					}
				}
			}
		};
		thread.start();
	}
}
